<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑技能' : '新增技能'"
    width="600px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="handleClose"
    custom-class="datav-dialog"
    :modal-class="'datav-modal'"
  >
    <dv-decoration-8 class="dialog-header-decoration" :reverse="true" />
    <dv-border-box-8 class="datav-form-container" :dur="5">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
        class="skill-form"
      >
        <!-- 标题 -->
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="form.title" 
            placeholder="请输入标题" 
            maxlength="50" 
            show-word-limit 
          />
        </el-form-item>
        
        <!-- 标签 -->
        <el-form-item label="标签" prop="tag">
          <div class="tags-container">
            <el-tag
              v-for="tag in displayTags"
              :key="tag"
              closable
              :disable-transitions="false"
              @close="handleTagClose(tag)"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputTagVisible"
              ref="tagInputRef"
              v-model="inputTagValue"
              class="tag-input"
              size="small"
              @keyup.enter="handleTagConfirm"
              @blur="handleTagConfirm"
              maxlength="20"
              placeholder="请输入标签，最多20个字符"
            />
            <el-button 
              v-else 
              class="button-new-tag tech-button" 
              size="small" 
              @click="showTagInput"
              :disabled="displayTags.length >= 5"
            >
              <el-icon><Plus /></el-icon> 添加标签
            </el-button>
            <div class="tag-tips">最多添加5个标签，每个标签不超过20个字符，系统会自动添加#前缀</div>
          </div>
        </el-form-item>
        
        <!-- 摘要 -->
        <el-form-item label="摘要" prop="summary">
          <el-input 
            v-model="form.summary" 
            type="textarea" 
            placeholder="请输入摘要内容" 
            maxlength="200" 
            show-word-limit 
            :rows="3"
          />
        </el-form-item>
        
        <!-- 内容 -->
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="form.content" 
            type="textarea" 
            placeholder="请输入详细内容" 
            maxlength="1000" 
            show-word-limit 
            :rows="6"
          />
        </el-form-item>
        
        <!-- 日期 -->
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
        </el-form-item>
        
        <!-- 浏览量 -->
        <el-form-item label="浏览量" prop="views">
          <el-input-number 
            v-model="form.views" 
            :min="0" 
            :precision="0"
            :step="1"
            class="number-input"
            controls-position="right"
          />
        </el-form-item>
        
        <!-- 点赞数 -->
        <el-form-item label="点赞数" prop="likes">
          <el-input-number 
            v-model="form.likes" 
            :min="0" 
            :precision="0"
            :step="1"
            class="number-input"
            controls-position="right"
          />
        </el-form-item>
        
        <!-- 启用状态 -->
        <el-form-item label="启用状态">
          <el-switch
            v-model="form.enable"
            active-text="开启"
            inactive-text="关闭"
            class="tech-switch"
          />
          <div class="switch-tip">控制该技能是否在前端展示</div>
        </el-form-item>
      </el-form>
    </dv-border-box-8>
    
    <template #footer>
      <dv-border-box-1 class="datav-dialog-footer-box">
        <div class="datav-dialog-footer">
          <el-button @click="handleClose" class="tech-button">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting" class="tech-button tech-button--primary">
            保存
          </el-button>
        </div>
      </dv-border-box-1>
    </template>
    <dv-decoration-8 class="dialog-footer-decoration" />
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { app, ensureLogin } from '../../utils/cloudbase'
import dayjs from 'dayjs'

export default {
  name: 'SkillFormDialog',
  components: {
    Plus
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    skillData: {
      type: Object,
      default: () => null
    }
  },
  emits: {
    'update:visible': (value) => typeof value === 'boolean',
    'refresh': null
  },
  setup(props, { emit }) {
    // 表单引用
    const formRef = ref(null)
    const tagInputRef = ref(null)
    
    // 对话框可见性
    const dialogVisible = computed({
      get: () => props.visible,
      set: (val) => emit('update:visible', val)
    })
    
    // 是否为编辑模式
    const isEdit = computed(() => !!props.skillData)
    
    // 表单数据
    const form = reactive({
      _id: '',
      id: '',
      title: '',
      tag: '',
      summary: '',
      content: '',
      date: dayjs().format('YYYY-MM-DD'),
      views: 0,
      likes: 0,
      enable: true
    })
    
    // 标签相关
    const inputTagVisible = ref(false)
    const inputTagValue = ref('')
    
    // 处理后的标签数组（用于显示）
    const displayTags = computed(() => {
      if (!form.tag) return []
      return form.tag.split(',')
        .map(tag => tag.trim())
        .filter(tag => tag !== '')
        .map(tag => tag.startsWith('#') ? tag : `#${tag}`)
    })
    
    // 提交状态
    const submitting = ref(false)
    
    // 表单验证规则
    const rules = {
      title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 1, max: 50, message: '标题长度应为1-50个字符', trigger: 'blur' }
      ],
      tag: [
        { required: true, message: '请至少添加一个标签', trigger: 'change' }
      ],
      summary: [
        { required: true, message: '请输入摘要', trigger: 'blur' },
        { max: 200, message: '摘要不能超过200个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入内容', trigger: 'blur' },
        { max: 1000, message: '内容不能超过1000个字符', trigger: 'blur' }
      ],
      date: [
        { required: true, message: '请选择日期', trigger: 'change' }
      ],
      views: [
        { required: true, message: '请输入浏览量', trigger: 'change' },
        { type: 'number', min: 0, message: '浏览量不能为负数', trigger: 'change' }
      ],
      likes: [
        { required: true, message: '请输入点赞数', trigger: 'change' },
        { type: 'number', min: 0, message: '点赞数不能为负数', trigger: 'change' }
      ]
    }
    
    // 重置表单
    const resetForm = () => {
      form._id = ''
      form.id = ''
      form.title = ''
      form.tag = ''
      form.summary = ''
      form.content = ''
      form.date = dayjs().format('YYYY-MM-DD')
      form.views = 0
      form.likes = 0
      form.enable = true
      
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
    
    // 监听编辑数据变化
    watch(() => props.skillData, (newVal) => {
      if (newVal) {
        // 填充表单数据
        form._id = newVal._id || ''
        form.id = newVal.id || ''
        form.title = newVal.title || ''
        form.tag = newVal.tag || ''
        form.summary = newVal.summary || ''
        form.content = newVal.content || ''
        form.date = newVal.date || dayjs().format('YYYY-MM-DD')
        form.views = parseInt(newVal.views) || 0
        form.likes = parseInt(newVal.likes) || 0
        form.enable = newVal.enable !== false // 默认为true
      } else {
        // 重置表单
        resetForm()
      }
    }, { immediate: true })
    
    // 关闭对话框
    const handleClose = () => {
      dialogVisible.value = false
      resetForm()
      // 如果是编辑模式，关闭时也触发刷新
      if (isEdit.value) {
        emit('refresh')
      }
    }
    
    // 标签相关方法
    const showTagInput = () => {
      inputTagVisible.value = true
      nextTick(() => {
        tagInputRef.value.focus()
      })
    }
    
    const handleTagClose = (tag) => {
      const tags = displayTags.value.filter(t => t !== tag)
      form.tag = tags.join(',')
    }
    
    const handleTagConfirm = () => {
      if (inputTagValue.value) {
        const tagText = inputTagValue.value.trim()
        if (tagText) {
          // 检查是否已存在该标签
          const formattedTag = tagText.startsWith('#') ? tagText : `#${tagText}`
          if (displayTags.value.includes(formattedTag)) {
            ElMessage.warning('标签已存在')
          } else if (displayTags.value.length >= 5) {
            ElMessage.warning('最多只能添加5个标签')
          } else {
            // 添加新标签
            const newTags = [...displayTags.value, formattedTag]
            form.tag = newTags.join(',')
          }
        }
      }
      inputTagVisible.value = false
      inputTagValue.value = ''
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (!valid) return
        
        try {
          submitting.value = true
          
          // 准备提交的数据
          const submitData = {
            title: form.title,
            tag: form.tag,
            summary: form.summary,
            content: form.content,
            date: form.date,
            views: form.views.toString(), // 转换为字符串
            likes: form.likes.toString(), // 转换为字符串
            enable: form.enable
          }
          
          // 调用云函数保存数据
          const action = isEdit.value ? 'update' : 'create'
          const functionData = {
            action,
            data: submitData
          }
          
          // 如果是编辑模式，添加_id
          if (isEdit.value && form._id) {
            functionData.data._id = form._id
            // 如果有id字段，也一并传入
            if (form.id) {
              functionData.data.id = form.id
            }
          }
          
          const res = await app.callFunction({
            name: 'admin-skills-list-crud',
            data: functionData
          })
          
          if (res.result && res.result.code === 0) {
            ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
            // 先触发刷新事件，再关闭对话框
            emit('refresh')
            console.log('触发刷新事件')
            setTimeout(() => {
              dialogVisible.value = false
            }, 100)
          } else {
            ElMessage.error(res.result?.message || (isEdit.value ? '编辑失败' : '添加失败'))
          }
        } catch (error) {
          console.error(isEdit.value ? '编辑失败:' : '添加失败:', error)
          ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
        } finally {
          submitting.value = false
        }
      })
    }
    
    return {
      formRef,
      tagInputRef,
      dialogVisible,
      isEdit,
      form,
      rules,
      submitting,
      displayTags,
      inputTagVisible,
      inputTagValue,
      handleClose,
      showTagInput,
      handleTagClose,
      handleTagConfirm,
      submitForm
    }
  }
}
</script>

<style scoped>
.skill-form {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
  color: #00c0ff;
}

.datav-form-container {
  width: 100%;
  height: auto;
  padding: 10px;
  background-color: rgba(0, 19, 47, 0.8);
}

:deep(.dv-border-box-8) {
  --dv-bb8-color: rgba(0, 192, 255, 0.6);
}

.datav-dialog-footer-box {
  width: 100%;
  height: 50px;
}

.datav-dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

:deep(.datav-dialog) {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
  border-radius: 4px !important;
  backdrop-filter: blur(5px);
  background: rgba(0, 19, 47) !important;
  overflow: hidden !important;
}

:deep(.datav-dialog .el-dialog) {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
}

:deep(.datav-dialog .el-dialog__header) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-bottom: 1px solid rgba(0, 192, 255, 0.3) !important;
  padding: 15px 20px !important;
  position: relative;
}

.dialog-header-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 30px;
  z-index: 1;
}

.dialog-footer-decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 30px;
  z-index: 1;
}

:deep(.datav-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: #00c0ff !important;
}

:deep(.datav-dialog .el-dialog__body) {
  background-color: rgba(0, 19, 47, 0.8) !important;
  padding: 20px !important;
  color: #00c0ff !important;
}

:deep(.datav-dialog .el-dialog__footer) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-top: 1px solid rgba(0, 192, 255, 0.3) !important;
  padding: 10px 20px !important;
  height: 70px;
}

:deep(.datav-modal) {
  background-color: rgba(0, 10, 30, 0.7) !important;
  backdrop-filter: blur(3px);
}

:deep(.dv-border-box-1) {
  --dv-bb1-color: rgba(0, 192, 255, 0.5);
}

:deep(.el-form-item__label) {
  color: #00c0ff !important;
}

:deep(.el-input__wrapper) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: none !important;
}

:deep(.el-input__inner) {
  color: #ffffff !important;
}

:deep(.el-textarea__inner) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  color: #ffffff !important;
}

:deep(.el-button.tech-button--primary) {
  background-color: rgba(0, 192, 255, 0.2) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #00c0ff !important;
}

:deep(.el-button.tech-button--primary:hover) {
  background-color: rgba(0, 192, 255, 0.4) !important;
  border-color: #00c0ff !important;
  color: #ffffff !important;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.5) !important;
}

:deep(.el-button.tech-button) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border-color: rgba(0, 192, 255, 0.3) !important;
  color: rgba(0, 192, 255, 0.8) !important;
}

:deep(.el-button.tech-button:hover) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #ffffff !important;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.tag-item {
  margin-right: 5px;
  margin-bottom: 5px;
  background-color: rgba(0, 30, 60, 0.6);
  border-color: rgba(0, 192, 255, 0.5);
  color: #ffffff;
}

.tag-input {
  width: 150px;
  margin-right: 10px;
  margin-bottom: 5px;
  vertical-align: bottom;
}

.tag-tips {
  width: 100%;
  font-size: 12px;
  color: rgba(0, 192, 255, 0.7);
  margin-top: 5px;
}

.button-new-tag {
  margin-bottom: 5px;
}

.date-picker {
  width: 100%;
}

:deep(.el-date-editor .el-input__wrapper) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: none !important;
}

:deep(.el-date-editor .el-input__inner) {
  color: #ffffff !important;
}

.number-input {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: none !important;
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  color: rgba(0, 192, 255, 0.8) !important;
  border-color: rgba(0, 192, 255, 0.5) !important;
}

:deep(.el-input-number__decrease:hover),
:deep(.el-input-number__increase:hover) {
  color: #00c0ff !important;
}

.tech-switch {
  --el-switch-on-color: #00c0ff;
  --el-switch-off-color: rgba(0, 30, 60, 0.6);
}

.switch-tip {
  font-size: 12px;
  color: rgba(0, 192, 255, 0.7);
  margin-top: 5px;
}

:deep(.el-select-dropdown) {
  background-color: rgba(0, 20, 40, 0.7) !important;
  border: 1px solid rgba(0, 192, 255, 0.3) !important;
}

:deep(.el-select-dropdown__item) {
  color: #ffffff;
  background-color: rgba(0, 20, 40, 0.7);
}

:deep(.el-select-dropdown__item.hover),
:deep(.el-select-dropdown__item:hover) {
  background-color: rgba(0, 192, 255, 0.2);
}

:deep(.el-select-dropdown__item.selected) {
  color: #00c0ff;
  background-color: rgba(0, 192, 255, 0.1);
}
</style>